//
//  CommentsInfoViewController.m
//  myhuibao
//
//  Created by lijun on 13-4-9.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "CommentsInfoViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "CommentCell.h"
#import "CommentDetailViewController.h"
#import "CommentsViewController.h"
#import "LoadMoreCell.h"
#import "OMGToast.h"
#import "RequestLoadingView.h"
@interface CommentsInfoViewController ()

@end

@implementation CommentsInfoViewController
@synthesize mainTable;
@synthesize req;
@synthesize reqMore;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
//    wqTable=mainTable;
   
	// Do any additional setup after loading the view.
}

-(void) viewWillAppear:(BOOL)animated
{
    pageIndex=1;
    NSString *spageIndex=[NSString stringWithFormat:@"%d",pageIndex];
    int merchantId=[[Config Instance] getMemberId];
    NSString *password=[[Config Instance] getPassword];
    NSString *sid=[NSString stringWithFormat:@"%d",merchantId];
    NSURL *url = [NSURL URLWithString:url_commentsList];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:sid forKey:@"memberID"];
    [req setPostValue:password forKey:@"password"];
    [req setPostValue:spageIndex forKey:@"pageIndex"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate: self];

    [req startAsynchronous];

}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//实现接口的方法
//-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
//{
//    UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
//    cell.imageView.image = [image copy];
//}

- (void)finishReq:(ASIHTTPRequest *)request
{
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    if(![[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"log"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;
    }
    tableDataArray = [dic valueForKey:@"data"];
//    NSLog(@"%@",tableDataArray);
    returnCount = [tableDataArray count];
    if (returnCount==0) {
        [OMGToast showWithText:@"近期无点评数据。" bottomOffset:100];
    }

    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];

}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isReqFinished = true;
    isReqMoreFinished = true;
}

#pragma 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 110;
    }else{
        return 40;
    }}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"CommentCellIdentifier";

    if([indexPath row] < ([tableDataArray count])) {
        
        CommentCell *cell = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell==nil)
        {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        cell.lbNickName.text = [item valueForKey:@"MERCHANT_NAME"];
        cell.lbName1.text=[NSString stringWithFormat:@"%@:",[item valueForKey:@"NAME1"]];
        cell.lbName2.text=[NSString stringWithFormat:@"%@:",[item valueForKey:@"NAME2"]];
        cell.lbName3.text=[NSString stringWithFormat:@"%@:",[item valueForKey:@"NAME3"]];
        cell.lbScore1.text = [NSString stringWithFormat:@"%d分",[[item valueForKey:@"1"] intValue]];
        cell.lbScore2.text = [NSString stringWithFormat:@"%d分",[[item valueForKey:@"2"] intValue]];
        cell.lbScore3.text =  [NSString stringWithFormat:@"%d分",[[item valueForKey:@"3"] intValue]];
        cell.score = [item valueForKey:@"AGREE"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"AGREE"] floatValue]];
        if ([item valueForKey:@"CONTENT"] !=nil && [item valueForKey:@"CONTENT"]!= [NSNull null]) {
            cell.lbContent.text = [item valueForKey:@"CONTENT"] ;
        }
        cell.lbTime.text = [item valueForKey:@"ADD_TIME"];
        cell.lbTime.hidden = false;
//        cell.lbmerchantname.text=@"商 户 名 称 ：";
//        cell.lbmerchantname.font=[UIFont fontWithName:@"STHeiti-Medium.ttc" size:4];
//        cell.merchantName = [item valueForKey:@"MERCHANT_NAME"];
//        cell.lbpay.text=@"交   易   号   ： ";
//        cell.lbpay.font=[UIFont fontWithName:@"STHeiti-Medium.ttc" size:4];
//        cell.payType = [NSString stringWithFormat:@"%d",[[item valueForKey:@"DEAL_ID"] intValue]] ;
//        cell.lbvalue.text=@"交  易  时  间   ： ";
//        cell.lbvalue.font= [UIFont fontWithName:@"STHeiti-Medium.ttc" size:2];
//        cell.addDate = [item valueForKey:@"DEAL_DATE"];
//        cell.lbdate.text=@"点 评 时 间  ： ";
//        cell.lbdate.font=[UIFont fontWithName:@"STHeiti-Medium.ttc" size:2];
//        cell.dealDate = [item valueForKey:@"ADD_TIME"];
        return cell;
        
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
            
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;

    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
//        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_commentsList,pageIndex++]] ;
//        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        int merchantId=[[Config Instance] getMemberId];
        NSString *password=[[Config Instance] getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",merchantId];
        NSURL *url = [NSURL URLWithString:url_commentsList];
        reqMore =[ASIFormDataRequest requestWithURL:url];
        [reqMore setPostValue:sid forKey:@"memberID"];
        [reqMore setPostValue:password forKey:@"password"];
        NSString *spageIndex=[NSString stringWithFormat:@"%d",++pageIndex];
        [reqMore setPostValue:spageIndex forKey:@"pageIndex"];
        [reqMore setShouldAttemptPersistentConnection:NO];
        [reqMore setDidFinishSelector:@selector(appendTableWith:)];
        reqMore.delegate = self;
        [reqMore startAsynchronous];

        isReqMoreFinished = false;
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
        //        [dic release];
        //        [array release];
        return;
    }else{
        CommentDetailViewController  *view = [[CommentDetailViewController alloc] initWithNibName:@"CommentDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        view.merchantType=[[item objectForKey:@"MERCHANTTYPE"] intValue];
        view.comments=item;
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
    }
    //其他cell的事件
}

-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isReqMoreFinished = true;;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//    isSearchMoreFinished = true;
}

- (IBAction)goBack:(id)sender {
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }
    if (!isReqMoreFinished){
        [reqMore clearDelegatesAndCancel];
        [reqMore cancel];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)OnShowConsumeList:(id)sender{
    CommentsViewController *view=[[CommentsViewController alloc]initWithNibName:@"CommentsViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
    
}
@end
